# 创建一个基础的商品管理组件
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关联非遗" prop="heritageId">
        <el-select v-model="queryParams.heritageId" placeholder="请选择关联非遗" clearable>
          <el-option
            v-for="item in heritageOptions"
            :key="item.heritageId"
            :label="item.heritageName"
            :value="item.heritageId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="商品状态" clearable>
          <el-option label="上架" value="0" />
          <el-option label="下架" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ich:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ich:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ich:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ich:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="商品图片" align="center" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.mainImage"
            :src="baseURL + scope.row.mainImage"
            :preview-src-list="[baseURL + scope.row.mainImage]"
            fit="cover"
            class="product-image"
            style="width: 60px; height: 60px"
          />
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
      <el-table-column label="关联非遗" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ getHeritageName(scope.row.heritageId) }}
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="库存数量" align="center" prop="stock" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
            {{ scope.row.status === '0' ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ich:product:edit']"
          >修改</el-button>
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ich:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="productForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联非遗" prop="heritageId">
              <el-select v-model="form.heritageId" placeholder="请选择关联非遗">
                <el-option
                  v-for="item in heritageOptions"
                  :key="item.heritageId"
                  :label="item.heritageName"
                  :value="item.heritageId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品图片" prop="mainImage">
          <image-upload v-model="form.mainImage" :limit="1" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="stock">
              <el-input-number v-model="form.stock" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="材质" prop="materials">
          <el-input v-model="form.materials" placeholder="请输入商品材质" />
        </el-form-item>
        <el-form-item label="制作工艺" prop="craft">
          <el-input v-model="form.craft" type="textarea" placeholder="请输入制作工艺" />
        </el-form-item>
        <el-form-item label="非遗元素" prop="ichElements">
          <el-input v-model="form.ichElements" type="textarea" placeholder="请输入非遗元素" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">上架</el-radio>
            <el-radio label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import { getCurrentInstance, ref, reactive, toRefs, onMounted } from 'vue';
import { listHeritage } from "@/api/ich/heritage";
import { listProduct, getProduct, addProduct, updateProduct, delProduct } from "@/api/ich/product";
import ImageUpload from '@/components/ImageUpload/index.vue';

const { proxy } = getCurrentInstance();

const productList = ref([]);
const heritageOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const baseURL = import.meta.env.VITE_APP_BASE_API;

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: undefined,
    heritageId: undefined,
    status: undefined
  },
  rules: {
    productName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    heritageId: [
      { required: true, message: "关联非遗不能为空", trigger: "change" }
    ],
    price: [
      { required: true, message: "价格不能为空", trigger: "blur" }
    ],
    stock: [
      { required: true, message: "库存数量不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品列表 */
function getList() {
  loading.value = true;
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取非遗项目列表 */
async function getHeritageOptions() {
  try {
    const response = await listHeritage();
    heritageOptions.value = response.rows.map(item => ({
      heritageId: item.heritageId,
      heritageName: item.heritageName
    }));
    console.log('非遗列表数据:', heritageOptions.value);
  } catch (error) {
    console.error('获取非遗列表失败:', error);
  }
}

/** 根据非遗ID获取非遗名称 */
function getHeritageName(heritageId) {
  const heritage = heritageOptions.value.find(item => item.heritageId === heritageId);
  return heritage ? heritage.heritageName : '';
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    productId: undefined,
    productName: undefined,
    heritageId: undefined,
    mainImage: undefined,
    price: 0,
    stock: 0,
    materials: undefined,
    craft: undefined,
    ichElements: undefined,
    status: "0"
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.productId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getHeritageOptions();
  open.value = true;
  title.value = "添加商品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const productId = row.productId || ids.value;
  getHeritageOptions();
  getProduct(productId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productForm"].validate(valid => {
    if (valid) {
      if (form.value.productId != undefined) {
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const productIds = row.productId || ids.value;
  proxy.$modal.confirm('是否确认删除商品编号为"' + productIds + '"的数据项？').then(function() {
    return delProduct(productIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`);
}

// 组件挂载时初始化
onMounted(async () => {
  try {
    loading.value = true;
    await getHeritageOptions();
    await getList();
  } catch (error) {
    console.error('初始化失败:', error);
  } finally {
    loading.value = false;
  }
});
</script> 